import { Module } from 'vuex';
import { SysMenu, useAuth, useMenu } from 'pf-component';
import { cacheUtils } from '@/constants/util/cache-utils';
import { RootModule } from '@/store/index';
import { initRouterForMenu } from '@/router';
const getFirst = (menus: SysMenu[], self: SysMenu): SysMenu => {
  return menus && menus.length ? getFirst(menus[0].children, menus[0]) : self;
};
type MenusModule = { allMenus: SysMenu[] };
export const menus: Module<MenusModule, RootModule> = {
  namespaced: true,
  state: {
    allMenus: cacheUtils.get('menus') || []
  },
  getters: {
    allMenus: (state: MenusModule, getters): SysMenu[] => {
      return state.allMenus;
    },
    index: (state: MenusModule): SysMenu => {
      return getFirst(state.allMenus, state.allMenus[0]);
    }
  },
  mutations: {
    INIT_MENUS: (state: MenusModule, payload: SysMenu[]) => {
      state.allMenus.splice(0, state.allMenus.length, ...payload);
      cacheUtils.set('menus', payload);
    }
  },
  actions: {
    async initMenusByAppId({ commit }, payload) {
      return useMenu()
        .list()
        .then((res: SysMenu[]) => {
          commit('INIT_MENUS', res);
          res && initRouterForMenu(res);
          return res;
        });
    }
  },
  modules: {}
};
